#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_gpio.h"
#include "hi_io.h"

#define SR501_GPIO 2        // HC-SR501 连接到 GPIO2
#define LED_GPIO 10         // LED 连接到 GPIO10

static void Hcsr501IoInit(void)
{
    // Initialize LED GPIO as output
    IoTGpioSetDir(LED_GPIO, IOT_GPIO_DIR_OUT);
    
    // Initialize SR501 GPIO as input
    IoTGpioSetDir(SR501_GPIO, IOT_GPIO_DIR_IN);
    // Enable pull-down for SR501 input
    hi_io_set_pull(SR501_GPIO, HI_IO_PULL_DOWN);
}

static void* Hcsr501Task(const char* arg)
{
    (void)arg;
    unsigned int state = 0;
    
    while (1) {
        // Read motion sensor state
        IoTGpioGetInputVal(SR501_GPIO, &state);
        
        // Control LED based on motion sensor state
        if (state == 1) {  // High level means motion detected
            IoTGpioSetOutputVal(LED_GPIO, 1);  // Turn on LED
             printf("Motion detected! LED ON\n");
        } else {
            IoTGpioSetOutputVal(LED_GPIO, 0);  // Turn off LED
            printf("No motion. LED OFF\n");
        }
        
        // Small delay to prevent busy waiting
        usleep(100000);  // 100ms delay
    }
    return NULL;
}

static void Hcsr501ExampleEntry(void)
{
    osThreadAttr_t attr;
    
    // Initialize GPIOs
    Hcsr501IoInit();
    
    attr.name = "Hcsr501Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = 25;
    
    if (osThreadNew((osThreadFunc_t)Hcsr501Task, NULL, &attr) == NULL) {
        printf("Failed to create Hcsr501Task!\n");
    }
}

SYS_RUN(Hcsr501ExampleEntry);